package com.yzt.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yzt.base.dto.ZTreeDTO;
import com.yzt.base.service.impl.BaseServiceImpl;
import com.yzt.sys.entity.Permission;
import com.yzt.sys.entity.RolePermission;
import com.yzt.sys.mapper.PermissionMapper;
import com.yzt.sys.service.IPermissionService;
import com.yzt.sys.service.IRolePermissionService;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author Y
 * @since 2021-01-21
 */
@Service
public class PermissionServiceImpl extends BaseServiceImpl<PermissionMapper, Permission> implements IPermissionService {

	@Autowired
	private IRolePermissionService rolePermissionService;

	@Override
	public List<ZTreeDTO> getZTree() {
		List<ZTreeDTO> list = new ArrayList<>();
		List<Permission> l = this.list(Wrappers.<Permission>lambdaQuery().isNull(Permission::getParentId));
		for (Permission p : l) {
			ZTreeDTO dto = new ZTreeDTO();
			dto.setId(p.getId());
			dto.setName(p.getName());
			dto.setOpen(true);
			getZTree(dto);
			list.add(dto);
		}
		return list;
	}

	public void getZTree(ZTreeDTO zTreeDTO) {
		List<ZTreeDTO> list = new ArrayList<>();
		List<Permission> l = this
				.list(Wrappers.<Permission>lambdaQuery().eq(Permission::getParentId, zTreeDTO.getId()));
		if (l.size() > 0) {
			zTreeDTO.setIsParent(true);
		}
		for (Permission p : l) {
			ZTreeDTO dto = new ZTreeDTO();
			dto.setId(p.getId());
			dto.setName(p.getName());
			getZTree(dto);
			list.add(dto);
		}
		zTreeDTO.setChildren(list);
	}

	@Override
	public List<Permission> getPermissions(List<Long> roleIds) {
		List<Long> permissionIds = rolePermissionService.listObjs(Wrappers.<RolePermission>lambdaQuery()
				.select(RolePermission::getPermissionId).in(RolePermission::getRoleId, roleIds), a -> {
					return Long.valueOf(a.toString());
				}).stream().distinct().collect(Collectors.toList());
		List<Permission> list = this.list(Wrappers.lambdaQuery(Permission.class).in(Permission::getId, permissionIds));
		return list;
	}

}
